<?php
namespace app\admin\controller;
use think\Db;
use think\Controller;
use app\common\controller\AdminBaseController;

class Index extends AdminBaseController
{
    public function index()
    {
    	
    	return $this->fetch();
    }
	
	//余额异常
	public function balance_trace(){
		$map['m.balance'] = ['>=',10];
		$map1['status_tinyint'] = 1;
		if(request()->isPost()){ 	
		 	$param = input('post.');
			if($param['name']){
				$map['m.agent_name'] = ['like', '%'.$param['name'].'%'];
			}
		}
		//$map1['add_time']=['<=',date('Y-m-d',time())];
		$ye=db("log_agent_charge")->where($map1)->field("agent_id,status_tinyint,order_type,sum(balance) as balance1")->group("agent_id")->buildSql();
    	$list=db("info_agent")->alias('m')
    	->join($ye."a","m.id=a.agent_id","INNER")->where($map)
    	->field("m.*,FORMAT(a.balance1,2) as balance1")->paginate(20);
		$this->assign('empty','<span class="empty">没有数据</span>');
        return $this->fetch('balance_trace', ['list' => $list]);
	}
	
	
    public function welcome(){
	   $users=db("info_user")->cache(30)->count();
	   $today_users=db("info_user")->whereTime('add_time', 'today')->cache(60)->count();
	   $week_users=db("info_user")->whereTime('add_time', 'week')->cache(60)->count();
	   $month_users=db("info_user")->whereTime('add_time', 'month')->cache(60)->count();
	   $agents=db("info_agent")->cache(30)->count();
	   $today_agents=db("info_agent")->whereTime('add_time', 'today')->cache(60)->count();
	   $week_agents=db("info_agent")->whereTime('add_time', 'week')->cache(60)->count();
	   $month_agents=db("info_agent")->whereTime('add_time', 'month')->cache(60)->count();
	   
	   $tj=db("sys_tongji")->find();
	   //当前账户余额
	   $balances=$tj['balances']-$tj['tx_balances'];
	   $this->assign("balances",$balances);
	   $user_scores=db("info_user")->cache(30)->sum("score");
	   $agent_scores=db("info_agent")->cache(30)->sum("score");
	   $oem_scores=db("info_oem")->cache(30)->sum("score");
	   $total_score=$user_scores+$agent_scores+$oem_scores;
	   $this->assign('total_scores',$total_score);
	   
	   $user_balance=db("info_user")->cache(30)->sum("balance");
	   $agent_balance=db("info_agent")->cache(30)->sum("balance");
	   $oem_balance=db("info_oem")->cache(30)->sum("balance");
	   $total_balance=$user_balance+$agent_balance+$oem_balance;
	   $this->assign('total_balance',$total_balance);
	   
	   $pts=db("admin_charge")->sum('balance');
	   $today_pts=db("admin_charge")->whereTime('add_time', 'today')->cache(30)->sum("balance");
	   $month_pts=db("admin_charge")->whereTime('add_time', 'month')->cache(30)->sum("balance");
	   $this->assign('pts',$pts);
	   $this->assign('month_pts',$month_pts);
	   $this->assign('today_pts',$today_pts);
	   
	   $logs=db('log_paylog_copy')->cache(30)->sum("balance");	   
	   $today_logs=db("log_paylog_copy")->whereTime('add_time', 'today')->cache(30)->sum("balance");
	   $week_logs=db("log_paylog_copy")->whereTime('add_time', 'week')->cache(30)->sum("balance");
	   $month_logs=db("log_paylog_copy")->whereTime('add_time', 'month')->cache(30)->sum("balance");
	   $this->assign("logs",$logs);
	   $this->assign("today_logs",$today_logs);
	   $this->assign("week_logs",$week_logs);
	   $this->assign("month_logs",$month_logs);
	   
	   $counts=db('log_paylog_copy')->cache(30)->count();
	   $today_counts=db("log_paylog_copy")->whereTime('add_time', 'today')->cache(30)->count();
	   $week_counts=db("log_paylog_copy")->whereTime('add_time', 'week')->cache(30)->count();
	   $month_counts=db("log_paylog_copy")->whereTime('add_time', 'month')->cache(30)->count();
	   $this->assign("counts",$counts);
	   $this->assign("today_counts",$today_counts);
	   $this->assign("week_counts",$week_counts);
	   $this->assign("month_counts",$month_counts);
	   
	   $this->assign("users",$users);
	   $this->assign("agents",$agents);
	   $this->assign("today_users",$today_users);
	   $this->assign("today_agents",$today_agents);
	   $this->assign("week_users",$week_users);
	   $this->assign("week_agents",$week_agents);
	   $this->assign("month_users",$month_users);
	   $this->assign("month_agents",$month_agents);
        return  $this->fetch();
    }
	
	//发送短信
	function test_sms(){
		
		//获取对应的短信模板
		$template = db('sms_template') ->where('id',9)->find();
		//短信模板所需参数
		$msg['name'] = 'sdfsd';
		
		//发送短信
		$msg = send_sms('15343353867', $template['tid'], json_encode($msg), $template['sign_name']);
	}
	
	
	//短信验证码
	/**
	 * 发送短信
	 * $mobile 手机号
	 * $template_no 模板编号(数据库主键)，注意不是模板ID
	 */
	function get_code($mobile, $template_no){
		// 获取短信模板
		$template = db('sms_template') -> find($template_no);
		// 如果是验证码类型，则生成6位验证码
		if($template['type'] == 1){
			$code = rand(100000, 999999);
			$template['params'] = str_replace('${code}', $code, $template['params']);
			$data['code'] = $code;
		}
		$msg = send_sms($mobile, $template['tid'], htmlspecialchars_decode($template['params']), $template['sign_name']);
		$data['mobile'] = $mobile;
		$data['title'] = $template['title'];
		$data['add_time'] = now_time();
		if(isset($msg->result)) {
			$data['message'] = '发送成功';
			db('sms_code')->insert($data);
			return $this->toSuccess('发送成功');
		}else{
			$data['result'] = 0;
			$data['message'] = '发送失败:'.$msg->sub_msg;
			db('sms_code')->insert($data);
			if($msg->sub_code == "isv.BUSINESS_LIMIT_CONTROL"){
				$err = "超过发送次数，请稍后再试";
			}else{
				$err = "发送失败";
			}
			return $this->toError(408, $err);
		}
	}
	
	
	
	//地图定位
	public function position(){

		$other_config=db('tg_admin_system')->where('name','other_config')->find();	
		
		$config_info=unserialize($other_config['value']);
		
		$this->assign('key',$config_info['lbs_key']);
        return  $this->fetch();
    }
	
	//图片上传样例
	public function uploading_test(){
    	
        return  $this->fetch();
    }
	
	//富文本编辑器
	public function wang_editor(){
		if(request()->isAjax()){
			$data = input('post.');
			$ret = db('sys_helps')->insert($data);
		}
		$data =  db('sys_helps')->where('id',13)->find();
		$data['content'] = html_entity_decode($data['content']);
		$this->assign('data',$data);
		return  $this->fetch();
	}
	
	
	
	
	
    
    public function adminshow(){
		$admin_id = session('admin_id');
		$data=Db::name('tg_auth_user')->find();
    	$this->assign('data',$data);
        return  $this->fetch();
    }
    
    
    public function log(){
        $admin_id = session('admin_id');
        $id=Db::name('tg_auth_group_access')->where('uid',$admin_id)->field('group_id')->find();
		$role = Db::name('tg_auth_group')->field('id')->where('id',$id['group_id'])->find();
		$where=[];
		if($role['id']!=1){
			$where['admin_name']=session('admin_name');
		}
        $lists=Db::name('tg_admin_log')->where($where)->order('add_time DESC')->paginate(8);
        $this->assign('list',$lists);
        return  $this->fetch();
    }
    //删除log
    public function logdel(){
        $data['id']=input('id');
	       $result =Db::name('tg_admin_log')->where('id', $data['id'])->delete();
	        if($result){
				 return  $this->success("成功","log",2);
	       }else{
	       		return $this->error("失败");
	       }
        return  $this->fetch();
    }
    
    
   public function config(){
   	$list=Db::name('tg_admin_system')->select();	
    	for($i=0;$i<count($list);$i++){
    		$value=unserialize($list[$i]['value']);
    		$name[$i]=$list[$i]['name'];
    		$this->assign('config'.$i,$value);
    	}
    return $this->fetch('config',['name'=>$name]);
    
   }
   
   public function save()
    {
    	$param=input('post.');
    	if(in_array('site_config',$param)){
    		$where['name']=$param['site_config'];
    	}
    	if(in_array('sms_config',$param)){
    		$where['name']=$param['sms_config'];
    	}
    	if(in_array('wechat_config',$param)){
    		$where['name']=$param['wechat_config'];
    	}
    	if(in_array('payment_config',$param)){
    		$where['name']=$param['payment_config'];
    	}
    	if(in_array('three_config',$param)){
    		$where['name']=$param['three_config'];
    	}
		if(in_array('other_config',$param)){
    		$where['name']=$param['other_config'];
    	}
		if(in_array('fx_config',$param)){
    		$where['name']=$param['fx_config'];
    	}
    	$value['value']=serialize($param);
    	$list=Db::name('tg_admin_system')->where($where)->update($value);
    	$this->success('保存成功' , url('config'));
    }
	
	
	
	//事务处理，需把表引擎类型改为innodb
	function test_db(){
		echo $_SERVER['REQUEST_URI'];
		$is_success = false;
		// 启动事务
		Db::startTrans();
		try{
			
			$res1 = db('test_db')->where('id',1032)->update(['code' => 123456]);
			$data = [
			'title' 		=> 'bar', 
			'mobile' 		=> 'foo',
			'code' 			=> 'foo',
			'message' 		=> 'foo',
			'add_time' 		=> 'foo',
			'aaa' 		=> 'foo',
			'update_time'	=>'foo'
			];
			$res2 = db('test_db')->insert($data);
		   	
		   	
			if($res1 && $res2){
				$is_success = true;
			}
		   
		} catch (\Exception $e) {
			echo '数据异常';
		}
		dump($is_success);
		if($is_success){
			 // 提交事务
		    Db::commit();   
		}else{
			 // 回滚事务
		    Db::rollback();
			echo '数据异常';
		}
	}
	
	
}
